<template>
  <div class="user-edit">
    <!-- Modal -->
    <!-- :styles="{top: '50%',transform: 'translateY(-50%)','border-radius': '15px',height: '80%','overflow-y': 'auto'}" -->
    <Modal
      :title="title"
      v-model="visible"
      width="1000"
      :styles="{ top: '20px', 'border-radius': '15px' }"
      :mask-closable="type == '0'"
      scrollable="true"
      transfer
    >
      <div class="drawer-content" v-if="visible">
        <div v-if="type == 2 || type == 1">
          <div>
            <Form
              ref="form"
              :model="form"
              :rules="ruleValidate"
              label-position="top"
            >
              <Row :gutter="32">
                <Col span="12">
                  <FormItem label="控制器序列号:" prop="equipSerial">
                    <Input v-model="form.equipSerial" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="会议室名称:" prop="title">
                    <Input v-model="form.title" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="会议室位置:" prop="address">
                    <Input v-model="form.address" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="门号：" prop="doorNo">
                    <Input v-model="form.doorNo" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="会议室面积：（㎡)" prop="area">
                    <Input v-model="form.area" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="容纳人数:" prop="count">
                    <Input v-model="form.count" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem
                    label="会议开始前提醒：（分钟）"
                    prop="remindStartBefore"
                  >
                    <Input v-model="form.remindStartBefore" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem
                    label="会议结束前提醒：（分钟）"
                    prop="remindEndBefore"
                  >
                    <Input v-model="form.remindEndBefore" />
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem
                    label="添加封面图片（建议尺寸：666*322）"
                    class="form-noheight"
                    prop="image"
                  >
                    <upload-pic-input v-model="form.image"></upload-pic-input>
                  </FormItem>
                </Col>
              </Row>
              <Row :gutter="32">
                <Col span="24">
                  <FormItem prop="meetRoomServesList" label="选择服务内容：">
                    <Select
                      v-model="form.meetRoomServesList"
                      multiple
                      placeholder="请选择"
                    >
                      <Option
                        v-for="item in scMeetRoomServeList"
                        :key="item.id"
                        :value="item.id"
                      >
                        <Avatar
                          shape="square"
                          :src="item.icon"
                          icon="ios-person"
                        />
                        {{ item.description }}
                      </Option>
                    </Select>
                  </FormItem>
                </Col>
              </Row>
              <Row :gutter="32">
                <Col span="24">
                  <FormItem
                    label="会议室顶部轮播图：（可以添加多张,建议尺寸:710*322）"
                    prop="sliderList"
                  >
                    <uploadPicThumb
                      v-model="form.sliderList"
                      :multiple="true"
                    />
                  </FormItem>
                </Col>
              </Row>
              <Row :gutter="32">
                <Col span="24">
                  <FormItem label="基础设施：" prop="baseDesc">
                    <Input
                      v-model="form.baseDesc"
                      type="textarea"
                      :autosize="{ minRows: 2, maxRows: 5 }"
                      placeholder="请填写会议室设备配置情况"
                    />
                  </FormItem>
                </Col>
                <Col span="24">
                  <FormItem label="会议室介绍，建议图片尺寸：500*300" prop="description">
                    <div class="cantainer">
                      <div class="avatar-uploader">
                        <Upload
                          :action="uploadFileUrl"
                          :headers="accessToken"
                          :on-success="handleSuccess"
                          :show-upload-list="false"
                        >
                          <div id="Uploadfiles"></div>
                        </Upload>
                      </div>
                      <quill-editor
                        class="editorCont"
                        v-model="form.description"
                        ref="myQuillEditor"
                        :options="editorOption"
                      >
                      </quill-editor>
                    </div>
                    <!-- <Input v-model="form.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请填写会议室介绍" /> -->
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </div>
        </div>

        <div v-if="type == 0">
          <!-- <div> -->
          <Form
            ref="form"
            :model="formSet"
            label-position="top"
            :rules="formSetRule"
          >
            <Row :gutter="32">
              <Col span="12">
                <FormItem label="会议室序号:" prop="code">
                  <Input v-model="formSet.code" />
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="会议室名称:" prop="title">
                  <Input v-model="formSet.title" readonly />
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="起订时间:" prop="minReserve">
                  <Select
                    v-model="formSet.minReserve"
                    transfer
                    placeholder="请选择"
                  >
                    <Option value="15">15分钟</Option>
                    <Option value="30">30分钟</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="单价: (元）" prop="price">
                  <Input v-model="formSet.price" placeholder="请填写数字" />
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="会议室清洁时间：（分钟）" prop="cleanMinutes">
                  <Input
                    v-model="formSet.cleanMinutes"
                    placeholder="请填写数字"
                  />
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="园区闸机进出时间：（分钟）" prop="inOutDoor">
                  <Input v-model="formSet.inOutDoor" placeholder="请填写数字" />
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="32">
              <Col span="24">
                <div class="add-section">
                  <span class="label">可用时间段：</span>
                  <div class="add-list">
                    <div
                      class="add-content"
                      v-for="(item, index) in formSet.timeList"
                      :key="index"
                    >
                      <div class="form-item">
                        <FormItem
                          :prop="'timeList.' + index + '.validStartDate'"
                          :rules="{
                            required: true,
                            message: '请输入开始时间',
                            trigger: 'blur',
                          }"
                        >
                          <Input
                            v-model="item.validStartDate"
                            placeholder="请输入开始时间（例：12:30）"
                          />
                        </FormItem>
                        <FormItem
                          :prop="'timeList.' + index + '.validEndDate'"
                          :rules="{
                            required: true,
                            message: '请输入结束时间',
                            trigger: 'blur',
                          }"
                        >
                          <Input
                            v-model="item.validEndDate"
                            placeholder="请输入结束时间（例：13:35）"
                          />
                        </FormItem>
                      </div>
                      <Button
                        type="primary"
                        v-if="index == 0"
                        @click="addTimeList"
                        ><Icon type="md-add" size="24"
                      /></Button>
                      <Button type="primary" v-else @click="subTimeList(index)"
                        ><Icon type="ios-trash-outline" size="24"
                      /></Button>
                    </div>
                  </div>
                </div>
              </Col>

              <Col span="24">
                <div class="add-section">
                  <span class="label">积分消费规则：</span>
                  <FormItem prop="integral">
                    <Select
                      v-model="formSet.integral"
                      transfer
                      multiple
                      placeholder="请选择"
                    >
                      <Option
                        v-for="item in integralData"
                        :key="item.id"
                        :value="item.id"
                        >{{ item.title }}</Option
                      >
                    </Select>
                  </FormItem>
                </div>
              </Col>
            </Row>

            <!-- <Divider /> -->

            <!-- <Row :gutter="32">
              <Col span="12"> 
                <Button type="primary" :loading="submitLoading" @click="submit">提交</Button>
                <Button @click="visible = false">取消</Button>
              </Col>
            </Row> -->
          </Form>
          <!-- </div> -->
        </div>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          size="large"
          :loading="submitLoading"
          @click="submit"
          >保存</Button
        >
        <Button size="large" @click="visible = false">取消</Button>
      </div>
      <!-- <div class="drawer-footer br" v-show="type != '0'">
        <Button type="primary" :loading="submitLoading" @click="submit"
          >提交</Button
        >
        <Button @click="visible = false">取消</Button>
      </div> -->
    </Modal>
  </div>
</template>

<script>
import {
  scMeetRoomAdd,
  scMeetRoomSetAdd,
  getScMeetRoomServeAll,
  scIntegralExpenseGetAll,
  uploadFile,
} from "@/api/index";
import {
  validateUsername,
  validateMobile,
  validatePassword,
} from "@/libs/validate";
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  ["link", "image", "video"], // 链接、图片、视频
];
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import departmentTreeChoose from "@/views/my-components/xboot/department-tree-choose";
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
import uploadPicThumb from "@/views/my-components/xboot/upload-pic-thumb";
import SetPassword from "@/views/my-components/xboot/set-password";
import dict from "@/views/my-components/xboot/dict";
// import { delete } from 'vue/types/umd';
export default {
  name: "user",
  components: {
    departmentTreeChoose,
    uploadPicInput,
    SetPassword,
    dict,
    uploadPicThumb,
    quillEditor,
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
    },
    formSetData: {
      type: Object,
    },
    type: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      accessToken: {},
      uploadFileUrl: uploadFile,
      editorOption: {
        placeholder: "请编辑相关内容",
        modules: {
          toolbar: {
            container: toolbarOptions,
            // container: "#toolbar",
            handlers: {
              image: function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  // console.log("触发input框选择图片文件: ",value);
                  document
                    .querySelector(".avatar-uploader #Uploadfiles")
                    .click();
                } else {
                  this.quill.format("image", false);
                }
              },
              // video:(val)=>{
              //    console.log("video");
              // }
            },
          },
        },
      },
      integralData: [], //积分类型
      scMeetRoomServeList: [], //会议室服务
      showIntegralScale: false,
      yuanqu: "", //园区里外
      roleList: [],
      visible: this.value,
      title: "",
      passColor: "",
      submitLoading: false,
      maxHeight: 510,
      form: {},
      formSet: {
        code: "",
        title: "",
        timeList: [{ id: "1", validStartDate: "", validEndDate: "" }],
        integral: [],
      },
      ruleValidate: {
        equipSerial: [
          { required: true, message: "请输控制器序列号", trigger: "blur" },
        ],
        title: [
          { required: true, message: "请输入会议室名称", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入会议室位置", trigger: "blur" },
        ],
        area: [
          { required: true, message: "请输入会议室面积", trigger: "blur" },
        ],
        count: [{ required: true, message: "请输入容纳人数", trigger: "blur" }],
        remindStartBefore: [
          { required: true, message: "请输入会议开始前提醒", trigger: "blur" },
        ],
        remindEndBefore: [
          { required: true, message: "请输入会议结束前提醒", trigger: "blur" },
        ],
        image: [
          { required: true, message: "请添加封面图片", trigger: "change" },
        ],
        meetRoomServesList: [
          {
            required: true,
            type: "array",
            message: "请选择服务内容",
            trigger: "change",
          },
        ],
        sliderList: [
          {
            required: true,
            type: "array",
            message: "请添加会议室顶部轮播图",
            trigger: "change",
          },
        ],
        baseDesc: [
          { required: true, message: "请输入基础设施", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入基础设施", trigger: "blur" },
        ],
        doorNo: [{ required: true, message: "请输入门号", trigger: "blur" }],
      },
      formSetRule: {
        // code: [
        //   { required: true, message: "请输控制器序列号", trigger: "blur" }
        // ],
        // title: [
        //   { required: true, message: "请输入会议室名称", trigger: "blur" }
        // ],
        minReserve: [
          { required: true, message: "请选择起订时间", trigger: "change" },
        ],
        price: [{ required: true, message: "请输入单价", trigger: "blur" }],
        cleanMinutes: [
          { required: true, message: "请输入会议室清洁时间", trigger: "blur" },
        ],
        inOutDoor: [
          {
            required: true,
            message: "请输入园区闸机进出时间",
            trigger: "blur",
          },
        ],
        integral: [
          {
            required: true,
            type: "array",
            message: "请选择积分消费规则",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    handleSuccess(res, file) {
      this.loading = false;
      if (res.success) {
        this.uploadSuccess(res.result);
      } else {
        this.$Message.error(res.message);
      }
    },
    uploadSuccess(res, fileUpDom) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      var _this = this;
      let quill = _this.$refs.myQuillEditor.quill;
      // 获取光标所在位置
      let length = 0;
      let Selection = quill.getSelection();
      if (Selection && Selection.index) {
        length = Selection.index;
      }
      // 如果上传成功
      console.log("res:", res);
      quill.insertEmbed(length, "image", res);
      quill.setSelection(length + 1);
    },
    init() {
      this.getScMeetRoomServeAllData();
      this.scIntegralExpenseGetAllData();
    },
    getScMeetRoomServeAllData() {
      getScMeetRoomServeAll().then((res) => {
        if (res.success) {
          this.scMeetRoomServeList = res.result;
        }
      });
    },
    scIntegralExpenseGetAllData() {
      scIntegralExpenseGetAll().then((res) => {
        if (res.success) {
          this.integralData = res.result;
        }
      });
    },

    submit() {
      // console.log( this.$refs.form)
      this.$refs.form.validate((valid) => {
        // console.log('valid',valid)
        // return
        if (valid) {
          if (this.type == "0") {
            let idList = {},
              dateList = {};
            this.formSet.integral.forEach((item, index) => {
              idList[
                "meetRoomSetIntegralExpenses[" + index + "].integralExpenseId"
              ] = item;
            });
            this.formSet.timeList.forEach((item, index) => {
              dateList["meetRoomSetValidTimes[" + index + "].validStartDate"] =
                item.validStartDate;
              dateList["meetRoomSetValidTimes[" + index + "].validEndDate"] =
                item.validEndDate;
            });
            let obj = {
              ...this.formSet,
              ...idList,
              ...dateList,
              meetRoomId: this.data.id,
            };
            scMeetRoomSetAdd(obj).then((res) => {
              if (res.success) {
                this.$Message.success("操作成功");
                this.visible = false;
                this.$emit("on-submit", true);
              }
            });
          } else {
            let apiType = "";
            if (this.type == "1") {
              //修改
              apiType = "update";
            } else if (this.type == "2") {
              //添加
              apiType = "add";
            }
            this.form.sliderImage = this.form.sliderList.join(",");
            let idList = {};
            this.form.meetRoomServesList.forEach((item, index) => {
              idList["meetRoomServes[" + index + "].id"] = item;
            });
            let obj = {
              ...this.form,
              ...idList,
            };
            scMeetRoomAdd(apiType, obj).then((res) => {
              if (res.success) {
                this.$Message.success("操作成功");
                this.visible = false;
                this.$emit("on-submit", true);
              }
            });
          }
        }
      });
    },
    setCurrentValue(value) {
      if (value === this.visible) {
        return;
      }
      // this.$refs.form.resetFields()
      if (this.type == "0") {
        this.title = "会议室设置";
        this.maxHeight =
          Number(document.documentElement.clientHeight - 121) + "px";
      } else if (this.type == "1" || this.type == "2") {
        this.title = this.type == "1" ? "修改会议室" : "添加会议室";
        this.maxHeight =
          Number(document.documentElement.clientHeight - 230) + "px";
      }
      // 清空数据
      if (this.type == "1") {
        //修改
        let meetRoomServesList = [];
        this.data.meetRoomServes.forEach((item) => {
          meetRoomServesList.push(item.id);
        });

        let obj = {
          ...this.data,
          meetRoomServesList,
          sliderList: this.data.sliderImage.split(","),
        };
        this.form = obj;
      } else if (this.type == "0") {
        // console.log('dassss',this.data)
        let meetRoomSetData = this.data.meetRoomSet;
        if (meetRoomSetData) {
          //修改设置
          for (let i in meetRoomSetData) {
            if (typeof meetRoomSetData[i] == "number") {
              meetRoomSetData[i] = meetRoomSetData[i].toString();
            }
          }
          let timeList = [],
            integral = [];
          meetRoomSetData.meetRoomSetValidTimes.forEach((item) => {
            timeList.push({
              validEndDate: item.validEndDate,
              validStartDate: item.validStartDate,
            });
          });
          meetRoomSetData.meetRoomSetIntegralExpenses.forEach((item) => {
            integral.push(item.integralExpenseId);
          });
          // integral
          delete this.data.meetRoomSet.meetRoomSetValidTimes;
          delete this.data.meetRoomSet.meetRoomSetIntegralExpenses;
          this.formSet = {
            ...this.data.meetRoomSet,
            timeList,
            integral,
          };
          // console.log('formSet:',this.formSet)
        } else {
          //添加设置
          this.formSet = {
            code: this.data.code || "",
            title: this.data.title || "",
            timeList: [{ id: "1", validStartDate: "", validEndDate: "" }],
            integral: [],
          };
        }
      } else {
        this.form = {};
      }
      this.visible = value;
    },
    addTimeList(type) {
      // if(type == 2 || type ==1) {
      // if(this.formSet.integral.length == this.integralData.length){
      //   this.$Message.success("最多添加"+this.integralData.length+"个")
      //   return
      // }
      // this.formSet.integral.push({id: Date.now(), vId: ''})
      // }else{
      this.formSet.timeList.push({ id: Date.now() });
      // }
    },
    subTimeList(index, type) {
      // if(type == 2) {
      //   this.formSet.integral.splice(index,1)
      // } else {
      this.formSet.timeList.splice(index, 1);
      // }
    },
  },
  watch: {
    value(val) {
      this.setCurrentValue(val);
    },
    visible(value) {
      this.$emit("input", value);
    },
    data(val) {
      this.formSet.title = val.title;
    },
    type() {
      // this.formSet = {
      //   code: '',
      //   timeList: [{id:'1', validStartDate: '', validEndDate: ''}],
      //   integral: []
      // }
      // this.form = {}
    },
  },
  mounted() {
    this.accessToken = {
      accessToken: this.getStore("accessToken"),
    };
    this.init();
  },
};
</script>

<style lang="less">
@import "@/styles/drawer-common.less";
.cantainer {
  background: #ffffff;
  border-radius: 5px;
  margin-top: 20px;
  padding-left: 40px;
  /deep/.editorCont {
    .ql-container strong {
      font-weight: bold !important;
    }
    .ql-container em {
      font-style: italic !important;
    }
  }
}

.quill-editor {
  height: 500px;
}
.ivu-modal {
  background-color: #fff;
}
.add-section {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  .label {
    width: 100px;
    margin-top: 6px;
  }
  .ivu-form-item,
  .add-list {
    flex: 1;
  }
}
.add-content {
  display: flex;
  // flex: 1;
  .form-item {
    display: flex;
    flex: 1;
    justify-content: space-between;
    .ivu-form-item {
      // width: 48%;
      margin-right: 20px;
    }
  }
  .ivu-form-item {
    flex: 1;
  }
  .ivu-btn {
    margin-right: 0;
  }
}
</style>

